/*
 * Copyright 2021-2022 the original author and authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.edu.tjnu.tutor.support.controller;

import cn.edu.tjnu.tutor.common.core.controller.BaseController;
import cn.edu.tjnu.tutor.common.core.domain.AjaxResult;
import cn.edu.tjnu.tutor.common.core.domain.view.PageVO;
import cn.edu.tjnu.tutor.system.domain.dto.ProfileDTO;
import cn.edu.tjnu.tutor.system.domain.entity.User;
import cn.edu.tjnu.tutor.system.domain.query.ProfileQuery;
import cn.edu.tjnu.tutor.system.domain.query.UserQuery;
import cn.edu.tjnu.tutor.system.domain.view.ProfileVO;
import cn.edu.tjnu.tutor.system.domain.view.UserVO;
import cn.edu.tjnu.tutor.system.service.UserService;
import cn.edu.tjnu.tutor.system.structure.UserStruct;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.annotation.Secured;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static cn.edu.tjnu.tutor.common.constant.RoleConst.*;

/**
 * 用户信息控制层。
 *
 * @author 王帅
 * @since 1.0
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController extends BaseController {

    private final UserStruct userStruct;
    private final UserService userService;

    @Secured(ROLE_STUDENT)
    @GetMapping("tutorPage")
    public AjaxResult<PageVO<UserVO>> tutorPage(@Validated UserQuery query) {
        if (isEmpty(query)) {
            query.setCollegeId(getCollegeId());
        }
        return pageSuccess(userService.pageByRoleKey(ROLE_TUTOR, query));
    }

    private boolean isEmpty(UserQuery query) {
        return query.getUserName() == null &&
                query.getUserCode() == null &&
                query.getCollegeId() == null;
    }

    @GetMapping("getInfo")
    @Secured({ROLE_STUDENT, ROLE_TEACHER})
    public AjaxResult<ProfileVO> getInfo(@Validated ProfileQuery query) {
        return success(userService.getProfile(query.getUserId(), query.getUserCode()));
    }

    /**
     * 修改个人信息。
     *
     * @param profileDTO 用户简介信息
     */
    @PutMapping("changeProfile")
    @Secured({ROLE_STUDENT, ROLE_TEACHER})
    public AjaxResult<Void> changeProfile(@Validated @RequestBody ProfileDTO profileDTO) {
        return toResult(userService.lambdaUpdate()
                .eq(User::getUserId, getUserId())
                .update(userStruct.toEntity(profileDTO)));
    }

}